package org.example.mrrope.service;

import lombok.extern.slf4j.Slf4j;
import org.example.mrrope.utils.DingUtil;
import org.example.mrrope.utils.FormUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 平板接口层
 */
@Service
@Slf4j
public class IpadApiService {

    @Autowired
    private DingUtil dingUtil;

    public JSONObject getUserPadeId(String workerName, String workshop, String factoryType) {
        //定义存储当前工人的派工单

        JSONObject searchJoOne = new JSONObject();
        searchJoOne.put("textField_mdcj570o",workerName);//平板号
        searchJoOne.put("radioField_m2sq6j8x",workshop+"车间");//车间
        searchJoOne.put("radioField_mapc5hem",factoryType);//工厂
        String user = null;
        try {
            user = dingUtil.yiDaSearchReturnData("FORM-93C571D25F5046B39ED7F91D1462046DG2SY", searchJoOne);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (user == null) {
            log.info("用户不存在");
            return null;
        }
        if (user.equals("[]")){
            log.info("用户不存在");
            return null;
        }
        if (user.length() < 0) {
            log.info("工人不存在");
            return null;
        }
        JSONArray jsonArray = new JSONArray(user);
        return jsonArray.getJSONObject(0).getJSONObject("formData");
    }

    public JSONArray getIpadApi(String workerName, String workshop, String factoryType) throws Exception {
        //查询作业表
        JSONArray bomUserZBJson = new JSONArray();
        JSONObject bomJsonObjectUser = this.getUserPadeId(workerName, workshop, factoryType);
        if (bomJsonObjectUser == null){
            return bomUserZBJson;
        }
        if (bomJsonObjectUser.isEmpty()){
            return bomUserZBJson;
        }
        workerName = bomJsonObjectUser.getString("textField_m2sq6j8u");
        //查询包装作业表
        JSONObject searchJo = new JSONObject();
        searchJo.put("radioField_mciyc78h","未完成");
        searchJo.put("radioField_mciuf704",factoryType);
        String s = dingUtil.yiDaSearchReturnData("FORM-66A0D556664246B69167368F08A4726BCMYJ", searchJo);
        JSONArray bomOneJson = new JSONArray(s);

        for (int i = 0; i < bomOneJson.length(); i++) {
            JSONObject bomJsonObject = bomOneJson.getJSONObject(i).getJSONObject("formData");
            JSONArray jsonArrOne = bomJsonObject.getJSONArray("tableField_m2co9jkz");
            //循环子表
            for (int j = 0; j < jsonArrOne.length(); j++) {
                JSONObject jsonObject = jsonArrOne.getJSONObject(j);
                JSONObject cuncujson = new JSONObject();
                //判断当前工人名称==当前工人
                if (jsonObject.has("textField_m2d0pu0u")) {
                    if (jsonObject.getString("textField_m2d0pu0u").equals(workerName)) {
                        String instanceId = null;
                        //查询子表
                        if (bomJsonObject.has("associationFormField_m2co9jky")) {
                            if (bomJsonObject.getString("associationFormField_m2co9jky").equals("\"[]\"")){
                                continue;
                            }
                            String substring = bomJsonObject.getString("associationFormField_m2co9jky").replaceAll("\\\\", "").substring(1);
                            if (substring.isEmpty() || substring.equals("null") || substring.equals("[]")){
                                continue;
                            }
                            instanceId = new JSONArray(substring.substring(0, substring.length() - 1)).getJSONObject(0).getString("instanceId");
                        } else if (bomJsonObject.has("associationFormField_m2co9jky_id")) {
                            if (bomJsonObject.getString("associationFormField_m2co9jky_id").equals("\"[]\"")){
                                continue;
                            }
                            String substring = bomJsonObject.getString("associationFormField_m2co9jky_id").replaceAll("\\\\", "").substring(1);
                            if (substring.isEmpty() || substring.equals("null") || substring.equals("[]")){
                                continue;
                            }
                            instanceId = new JSONArray(substring.substring(0, substring.length() - 1)).getJSONObject(0).getString("instanceId");
                        }
                        if (instanceId != null) {
                            cuncujson.put("PgdId", bomJsonObject.has("textField_m2dhkdsr") ? bomJsonObject.getString("textField_m2dhkdsr") : null);//派工单ID
                            cuncujson.put("SO", bomJsonObject.has("textField_m2d0pu16") ? bomJsonObject.getString("textField_m2d0pu16") : null);//SO号
                            cuncujson.put("InstanceId", instanceId);//instanceId
                            cuncujson.put("BaoZao", bomJsonObject.has("textareaField_lvxftd6b") ? bomJsonObject.get("textareaField_lvxftd6b") : null);//包装方式
                            cuncujson.put("Cptype", bomJsonObject.has("textareaField_mauymer2") ? bomJsonObject.getString("textareaField_mauymer2") : null);//产品规格
                            cuncujson.put("ACName", bomJsonObject.has("textField_lzcc6a1q") ? bomJsonObject.getString("textField_lzcc6a1q") : null);//产品名称
                            String ACImg = null;
                            if (bomJsonObject.has("imageField_lwt597ic")) {
                                ACImg = bomJsonObject.getString("imageField_lwt597ic");
                                JSONArray jsonArray = new JSONArray(ACImg);
                                String ACImgTow =  "https://ibzgkv.aliwork.com"+ jsonArray.getJSONObject(0).getString("url");
                                String fjNotLoginUrl = dingUtil.getFjNotLoginUrl(ACImgTow);
                                cuncujson.put("ACImg", fjNotLoginUrl);
                                cuncujson.put("ImgUUid", jsonArray.getJSONObject(0).getString("fileUuid"));
                            }
                            cuncujson.put("AC", bomJsonObject.has("textField_lwt597ig") ? bomJsonObject.getString("textField_lwt597ig") : null);//AC号
                            cuncujson.put("Cname", bomJsonObject.has("textField_lwt4miut") ? bomJsonObject.getString("textField_lwt4miut") : null);//客户名称
                            bomUserZBJson.put(cuncujson);
                            break;
                        }

                    }
                }
            }
        }
        //拿到当前工人的派工单
        //查询缴库单
//        String string = .toString();
        return bomUserZBJson;
    }

    /**
     * 新增工人缴库
     * @param userName
     * @param number
     * @return
     */
    public String inserWorkjiaoKu(String userName,String workshop,String factory,int number, String instanceId) {
        String yiDaPaiGonString = null ;
//        JSONObject jsonMap = new JSONObject(map);
        try {
            //查询当前派工单是否还可以继续派工
            String paiGong = dingUtil.getYidaById(instanceId);
            JSONObject paiGonJson = new JSONObject(paiGong);
            if (paiGonJson.has("numberField_m5f5gz4x")){
                if (paiGonJson.getInt("numberField_m5f5gz4x")<0){
                    return "派工已满";
                }
            }
            JSONObject jsonPg = new JSONObject();
            String so = paiGonJson.getString("textField_luga5zz1");
            String fromUuid = "FORM-3A8D681A77094B6DAF95EBB52ABF301DGFLW";
            // 通过调用FormUtils的getAssociationFormField方法，根据fromUuid、title和id获取关联表单字段的JSON数组
            JSONArray jsonArrayOne = FormUtils.getAssociationFormField(fromUuid, so, instanceId);
            jsonPg.put("associationFormField_m2cokczi", jsonArrayOne);//关联派工单
            jsonPg.put("imageField_m2cokczy", paiGonJson.has("imageField_lwt597ic")?paiGonJson.get("imageField_lwt597ic"):null);//成品图片
            jsonPg.put("textField_m2cokczw", paiGonJson.has("textField_lwt597ig")?paiGonJson.get("textField_lwt597ig"):null);//AC号
            jsonPg.put("textField_m2cokczx", paiGonJson.has("textField_lzcc6a1q")?paiGonJson.get("textField_lzcc6a1q"):null);//成品名称
            jsonPg.put("textField_m2cokczz", so);//计划内SO号
            jsonPg.put("textField_m2cokd00", paiGonJson.has("textField_lwt4miut")?paiGonJson.get("textField_lwt4miut"):null);//客户名称\
//            LocalDate now = LocalDate.now();
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//            LocalDateTime currentDateTime = LocalDateTime.now();
//            String formattedDate = currentDateTime.format(formatter);
            // 格式化当前日期
//            jsonPg.put("dateField_m2cokd02", new Date());//缴库日期
            jsonPg.put("textField_m2daf1kp", paiGonJson.has("textField_m2u824xc")?paiGonJson.get("textField_m2u824xc"):null);//PO号
            jsonPg.put("textField_m2dby2be", paiGonJson.has("textareaField_mauymer2")?paiGonJson.get("textareaField_mauymer2"):null);//规格描述
            jsonPg.put("numberField_m5qraf14", paiGonJson.has("numberField_m5qqg5lf")?paiGonJson.get("numberField_m5qqg5lf"):null);//外箱装量
            jsonPg.put("textField_m5nku36q", so);//分配SO号
            jsonPg.put("textField_m5nku36v", paiGonJson.has("textField_m2u824xc")?paiGonJson.get("textField_m2u824xc"):null);//PO号
//            jsonPg.put("numberField_m2diqzka", number);//总入库数量
//            jsonPg.put("numberField_m2diqzk9", 1);//总入库件数
            jsonPg.put("numberField_m3etnk8a", number);//总上缴数量
            jsonPg.put("radioField_mann5ewv", paiGonJson.has("radioField_mann5ewv")?paiGonJson.get("radioField_mann5ewv"):null);//生产工厂
            Double gonJia = paiGonJson.has("numberField_lyz73gl1")?paiGonJson.getDouble("numberField_lyz73gl1"):0;
            jsonPg.put("numberField_m2diqzk8", gonJia);//工价
            jsonPg.put("textField_m2dfkkre", paiGonJson.has("serialNumberField_m2ua3wlv")?paiGonJson.get("serialNumberField_m2ua3wlv"):null);//派工单流水号
            jsonPg.put("numberField_m33xk4sg", paiGonJson.has("numberField_lzcbrvgb")?paiGonJson.get("numberField_lzcbrvgb"):null);//包装成本价（箱）
            jsonPg.put("tableField_lwed3a1x", paiGonJson.has("tableField_lwed3a1x")?paiGonJson.get("tableField_lwed3a1x"):null);//半成品信息
            jsonPg.put("tableField_lxwy02ud", paiGonJson.has("tableField_lxwy02ud")?paiGonJson.get("tableField_lxwy02ud"):null);//包材信息
            //查询工人表
            ArrayList<JSONObject> jsonGrenArray = new ArrayList<>();
            JSONObject searchJo = new JSONObject();
//            searchJo.put("textField_m2sq6j8u", userName);
            searchJo.put("textField_mdcj570o",userName);//平板号
            searchJo.put("radioField_mapc5hem", factory);
            searchJo.put("radioField_m2sq6j8x",workshop+"车间");
            String ss2 = dingUtil.yiDaSearchReturnData("FORM-93C571D25F5046B39ED7F91D1462046DG2SY", searchJo);
            JSONArray grOneJson = new JSONArray(ss2);
            if (grOneJson.length() < 0) {
                return "工人不存在";
            }
            if (grOneJson.length() > 1) {
                return "工人存在多个";
            }
            JSONObject grJsonObject = grOneJson.getJSONObject(0).getJSONObject("formData");
            String grInstanceId = grOneJson.getJSONObject(0).getString("formInstanceId");
            userName = grJsonObject.getString("textField_m2sq6j8u");
            JSONObject jsonGren = new JSONObject();
            String fromUuidGr = "FORM-3A8D681A77094B6DAF95EBB52ABF301DGFLW";
            // 通过调用FormUtils的getAssociationFormField方法，根据fromUuid、title和id获取关联表单字段的JSON数组
            JSONArray jsonArrayGr = FormUtils.getAssociationFormField(fromUuidGr, userName, grInstanceId);
            jsonGren.put("associationFormField_m2st5pej",jsonArrayGr);//工人组长
            jsonGren.put("numberField_m2cokczl",number);//上缴数量
            jsonGren.put("textField_m2st5pel",grJsonObject.get("serialNumberField_m2sq6j8w"));//工号
            jsonGren.put("numberField_m2st5pem",gonJia*number);//工资
            jsonGren.put("textField_m2st5pek",userName);//工人名称
            jsonGren.put("textField_m3etnk89", grInstanceId);//uuid
            jsonGrenArray.add(jsonGren);
            jsonPg.put("tableField_m2dbbxf3", jsonGrenArray);//工人表
            yiDaPaiGonString = dingUtil.startInstance(jsonPg, "02216664383638207271", "FORM-43D5985B0AC9495093B7F60F95BE8A07Y05F");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return yiDaPaiGonString;
    }

    /**
     * selectWorkerXianQin
     * @param objetId
     * @return
     */
    public String selectWorkerXianQin(String objetId) {
        JSONObject returnJson = new JSONObject();
        try {
            String paiGong = dingUtil.getYidaById(objetId);
            JSONObject paiGongJson = new JSONObject(paiGong);
            returnJson.put("PgdId", paiGongJson.has("serialNumberField_m2ua3wlv") ? paiGongJson.getString("serialNumberField_m2ua3wlv") : null);//派工单ID
            returnJson.put("SO", paiGongJson.has("textField_luga5zz1") ? paiGongJson.getString("textField_luga5zz1") : null);//SO号
            returnJson.put("InstanceId", objetId);//instanceId
            returnJson.put("BaoZao", paiGongJson.has("textareaField_lvxftd6b") ? paiGongJson.get("textareaField_lvxftd6b") : null);//包装
            returnJson.put("Cptype", paiGongJson.has("textareaField_mauymer2") ? paiGongJson.getString("textareaField_mauymer2") : null);//产品规格
            returnJson.put("ACName", paiGongJson.has("textField_lzcc6a1q") ? paiGongJson.getString("textField_lzcc6a1q") : null);//产品名称
//            returnJson.put("ACImg", paiGongJson.has("imageField_lwt597ic") ? paiGongJson.getString("imageField_lwt597ic") : null);//产品图片
            returnJson.put("AC", paiGongJson.has("textField_lwt597ig") ? paiGongJson.getString("textField_lwt597ig") : null);//AC号
            returnJson.put("Cname", paiGongJson.has("textField_lwt4miut") ? paiGongJson.getString("textField_lwt4miut") : null);//客户名称
            JSONArray jsonArrayBom = new JSONArray();
            if(paiGongJson.has("tableField_lwed3a1x")){
                JSONArray jsonArray = paiGongJson.getJSONArray("tableField_lwed3a1x");
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonBom = jsonArray.getJSONObject(i);
                    JSONObject jsonBomTow = new JSONObject();
                    jsonBomTow.put("bomId", jsonBom.get("textField_lujgt592"));
                    jsonBomTow.put("bomName", jsonBom.get("textField_lwbmqipz"));
                    jsonBomTow.put("bomGge", jsonBom.get("textField_lujgt57g"));
                    jsonArrayBom.put(jsonBomTow);
                }
            }
            returnJson.put("BBom",jsonArrayBom);//半成品
//            returnJson.put("BBom",paiGongJson.has("tableField_lwed3a1x")?paiGongJson.get("tableField_lwed3a1x"):null);//半成品
            JSONArray jsonArrayBaoCai = new JSONArray();
            if(paiGongJson.has("tableField_lxwy02ud")){
                JSONArray jsonArray = paiGongJson.getJSONArray("tableField_lxwy02ud");
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonBom = jsonArray.getJSONObject(i);
                    JSONObject jsonBomTow = new JSONObject();
                    jsonBomTow.put("bcId", jsonBom.get("textField_lxwy02u6"));
                    jsonBomTow.put("bcName", jsonBom.get("textField_lxwy02u5"));
                    jsonBomTow.put("bcGge", jsonBom.get("textField_lxwy02u7"));
                    jsonArrayBaoCai.put(jsonBomTow);
                }
            }
            returnJson.put("BaoCai",jsonArrayBaoCai);//包材
//            returnJson.put("BaoCai",paiGongJson.has("tableField_lxwy02ud")?paiGongJson.get("tableField_lxwy02ud"):null);//包材
            returnJson.put("Count",paiGongJson.has("numberField_lwt597ik")?paiGongJson.get("numberField_lwt597ik"):null);//总数
            returnJson.put("XsNumber",paiGongJson.has("numberField_lwt597ij")?paiGongJson.get("numberField_lwt597ij"):null);//箱数
            returnJson.put("NeDai",paiGongJson.has("numberField_lujhx4e3")?paiGongJson.get("numberField_lujhx4e3"):null);//内袋装量
            returnJson.put("WaiXian",paiGongJson.has("numberField_m5qqg5lf")?paiGongJson.get("numberField_m5qqg5lf"):null);//外箱装量
            returnJson.put("Workload",paiGongJson.has("numberField_m5f5gz4x")?paiGongJson.get("numberField_m5f5gz4x"):null);//工作量
            returnJson.put("Cname",paiGongJson.has("textField_lwt4miut")?paiGongJson.get("textField_lwt4miut"):null);//客户名称
            returnJson.put("GonJia",paiGongJson.has("numberField_lyz73gl1")?paiGongJson.get("numberField_lyz73gl1"):null);//工价
            returnJson.put("GonCan",paiGongJson.has("radioField_mann5ewv")?paiGongJson.get("radioField_mann5ewv"):null);//工厂、
            returnJson.put("PO", paiGongJson.has("textField_m2u824xc")?paiGongJson.get("textField_m2u824xc"):null);//PO号
            returnJson.put("Bz", paiGongJson.has("textareaField_lw61w5oe")?paiGongJson.get("textareaField_lw61w5oe"):null);//备注
            returnJson.put("HuoId", paiGongJson.has("textField_m2uama11")?paiGongJson.get("textField_m2uama11"):null);//货号
            returnJson.put("ChengBenXian", paiGongJson.has("numberField_lzcbrvgb")?paiGongJson.get("numberField_lzcbrvgb"):null);//包装成本价（箱）
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return returnJson.toString();
    }













    /**
     * 查询当前工人的包装派工单
     *
     * @param workerName 工人名称
     * @return
     */
    public String packagingWorkOrder(String workerName) {
        //查询工人派工
        try {
            JSONObject searchJo = new JSONObject();
            String s = dingUtil.yiDaSearchReturnData("FORM-66A0D556664246B69167368F08A4726BCMYJ", searchJo);
            JSONArray bomOneJson = new JSONArray(s);
            for (int i = 0; i < bomOneJson.length(); i++) {
                JSONObject bomJsonObject = bomOneJson.getJSONObject(i).getJSONObject("formData");
                String inId = bomOneJson.getJSONObject(i).getString("formInstanceId");
                String instanceId = null;
                //查询子表
                if (bomJsonObject.has("associationFormField_m2co9jky")) {
                    String substring = bomJsonObject.getString("associationFormField_m2co9jky").replaceAll("\\\\", "").substring(1);
                    instanceId = new JSONArray(substring.substring(0, substring.length() - 1)).getJSONObject(0).getString("instanceId");
                } else if (bomJsonObject.has("associationFormField_m2co9jky_id")) {
                    String substring = bomJsonObject.getString("associationFormField_m2co9jky_id").replaceAll("\\\\", "").substring(1);
                    instanceId = new JSONArray(substring.substring(0, substring.length() - 1)).getJSONObject(0).getString("instanceId");
                }
                if (instanceId != null) {
                    //AC表
                    String bomItem = null;
                    bomItem = dingUtil.getYidaById(instanceId);
                    //查询派工单是否已完成
                    JSONObject jsonObject = new JSONObject();
                    if (bomItem != null){
                        JSONObject bomItemJson = new JSONObject(bomItem);
                        if (bomItemJson.has("numberField_m5f5gz4v")) {
                            if (bomItemJson.getInt("numberField_m5f5gz4v") <= 0) {
                                //更新
                                jsonObject.put("radioField_mciyc78h", "已完成");
                            }else{
                                jsonObject.put("radioField_mciyc78h", "未完成");
                            }
                        }else{
                            jsonObject.put("radioField_mciyc78h", "未完成");
                        }
                    }
                    dingUtil.UpdateYiDa(inId, jsonObject);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return "ok";
    }



}
